package com.example.demo.blockqueue;

import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

/**
 * @desc: <br/>
 * @author: Jingbo Hu<br/>
 * @time：2021年01⽉21⽇<br/>
 * @version：v1.0.0<br>
 */
public class SemaphoreDemo {

    private static Semaphore semaphore = new Semaphore(5);

    public static void main(String[] args) {
        for (int i = 0; i < 20; i++) {
            new Worker(semaphore).start();
        }
    }
}

class Worker extends Thread {

    Semaphore semaphore;

    public Worker(Semaphore semaphore) {
        this.semaphore = semaphore;
    }

    @Override
    public void run() {
        try {
            semaphore.acquire();
            System.out.println("正在生产......");
            TimeUnit.SECONDS.sleep(2);
            semaphore.release();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
